import axios from '@/util/ajax'
import Cookies from 'js-cookie'
import { LoginUsers, Users } from '../../../mock/data/user';
import { Message } from 'element-ui';

const state = {
    // uid
    uid: '',
    // 用户名
    name: '',
    // token
    token: '',
    // 角色分组
    role: ''
        // 头像
        // avatar: ''
}

const getters = {}

const mutations = {
    setUID: (state, data) => {
        if (data) {
            Cookies.set('uid', data)
        } else {
            Cookies.remove('uid')
        }
        state.uid = data
    },
    setName: (state, data) => {
        if (data) {
            Cookies.set('name', encodeURIComponent(data))
        } else {
            Cookies.remove('name')
        }
        state.name = data
    },
    setToken: (state, data) => {
        if (data) {
            Cookies.set('tokenAcess', data)
        } else {
            Cookies.remove('tokenAcess')
        }
        state.token = data
    },
    setRole: (state, data) => {
        if (data) {
            localStorage.setItem('role', data)
        } else {
            localStorage.remove('role')
        }
        state.role = JSON.parse(data)
    }
}

const actions = {
    //登录

    // 用户登录
    requestLogin({ commit, rootState }, userInfo) {
        return new Promise((resolve, reject) => {
            // 存储权限列表
            let { id, username, password, name } = userInfo;
            commit('setUID', id)
            commit('setName', username)
            commit('setToken', '11')
            commit('setRole', JSON.stringify(name))
            resolve(userInfo)
        })
    },
    // 登出
    logout({ commit }) {
        return new Promise((resolve) => {
            commit('setUID', '')
            commit('setName', '')
            commit('setToken', '')
            localStorage.removeItem("menu")
            localStorage.removeItem("role")
            localStorage.removeItem("user")
            resolve()
        })
    },
    // 重新登录
    relogin({ commit }) {
        return new Promise((resolve) => {
            // TODO 问题严重，重新登录需要字段不明，但肯定不能保存token
            commit('setUID', Cookies.get('uid'))
            commit('setName', decodeURIComponent(Cookies.get('name')))
            commit('setToken', Cookies.get('tokenAcess'))
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}